
using QdbUnit;
using QdbUnit.Extensions;
using QdbUnit.Extensions.Fixtures;
using Qdb.Config;
using Qdb.Internal;
using Qdb.Internal.Slots;
using Qdb.Tests.Common.Freespace;

namespace Qdb.Tests.Common.Freespace
{
	public class FreespaceManagerReopenTestCase : AbstractQdbTestCase, IOptOutMultiSession
		, IOptOutDefragSolo
	{
		private static int Size = 199331;

		public static void Main(string[] args)
		{
			new FreespaceManagerReopenTestCase().RunSolo();
		}

		/// <exception cref="System.Exception"></exception>
		protected override void Configure(IConfiguration config)
		{
			base.Configure(config);
			config.BTreeNodeSize(4);
			config.FlushFileBuffers(false);
		}

		// this just make the test faster
		/// <exception cref="System.Exception"></exception>
		public virtual void Test()
		{
			Slot testSlot = LocalContainer().GetSlot(Size);
			Slot reserveSlot = LocalContainer().GetSlot(Size / 2);
			Reopen();
			LocalContainer().Free(testSlot);
			LocalContainer().Free(reserveSlot);
			Reopen();
			Slot slot1 = LocalContainer().GetSlot(Size);
			Assert.IsTrue(Overlap(testSlot, slot1));
			Reopen();
			Slot slot2 = LocalContainer().GetSlot(Size);
			Assert.IsFalse(Overlap(testSlot, slot2));
		}

		private bool Overlap(Slot slot, Slot other)
		{
			Slot first = slot.Address() < other.Address() ? slot : other;
			Slot second = slot.Address() > other.Address() ? slot : other;
			return first.Address() + first.Length() >= second.Address();
		}

		private LocalObjectContainer LocalContainer()
		{
			return ((LocalObjectContainer)Db());
		}
	}
}
